package cn.kgc.springmvc.day04.handlers;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/11/13
 * @description   web项目中的全局异常处理类    定义不同异常的处理方案
 * 后续项目中不管在任何方法中抛出异常 均由全局异常处理完成
 *   @ControllerAdvice    标识当前类是全局异常处理类
 *
 *   @ResponseBody  +  @ControllerAdvice   =   @RestControllerAdvice
 */
// @ControllerAdvice
// @ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler({NullPointerException.class})
    public Map<String,Object> nullPointerExceptionHandler(NullPointerException e){

        e.printStackTrace();

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",110);
        result.put("message","服务器繁忙,请刷新重试");

        return  result;
    }

    @ExceptionHandler({ArrayIndexOutOfBoundsException.class})
    public Map<String,Object> arrayIndexOutOfBoundsExceptionHandler(ArrayIndexOutOfBoundsException e){

        e.printStackTrace();

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",110);
        result.put("message","数组下标越界了");

        return  result;
    }


    @ExceptionHandler({Exception.class})
    public Map<String,Object> otherExceptionHandler(Exception e){

        e.printStackTrace();

        HashMap<String, Object> result = new HashMap<>();
        result.put("code",110);
        result.put("message","出现异常了,什么异常不清楚...");

        return  result;
    }



}
